#!/bin/bash

http=http://tool.oschina.net/uploads/apidocs/jdk-zh/
workdir=${JAVA_ZH_API-~/java-zh-api}
index=$workdir/index
apiDir=$workdir/api

err_exit() {
    echo -e $1
    exit $2
}

# 生成索引文件
genIndex() {
    local netfile=allclasses-frame.html
    test -e $netfile || wget $http$netfile
    sed -rn 's/.*class="FrameItemFont">(.*)<\/font>.*/\1/p' $netfile > $index
    sed -i 's/<br \/>/\n/g' $index
    sed -i -r 's/.*href="(.*).html".*/\1.html/' $index
    vim $index "+:normal ,ws" "+:wq"
    sed -i '/^$/d' $index
}

# 下载所有类文件
downApi() {
    test -e $index || genIndex
    test -d $apiDir || mkdir $apiDir
    local savefile savedir

    while read file ; do
        savedir=$apiDir/${file%/*}
        test -d $savedir || mkdir -p $savedir
        savefile=$savedir/${file##*/}
        test -e $savefile && continue
        wget -q $http$file -O $savefile
        echo "$file 下载完成..."
    done < $index
}

# 生成对应包的路径
genPackagePath() {
    local file savefile opfile

    while read file ; do
        savedir=$apiDir/${file%/*}
        test -d $savedir || mkdir -p $savedir
        opfile=$apiDir/${file##*/}
        test -e $opfile || mv $opfile $savedir/ -v
    done < $index
}

# 按类名模糊查找
# declare -A list
declare -a list

getFindList() {
    local key="$1"
    local name line i

    list=()
    i=1
    for line in $(egrep -i "$key" $index)
    do
        name=${line##*/}
        name=${name%.html*}
        # echo $name $line
        list[$i]=$name:$line
        let i++
    done
}

showList() {
    local name i=1
    echo -e "查找 \033[31;1m$1\033[0m 到的相关类名: "
    for name in ${list[*]} ; do
        printf "\033[33;1m%6d:\033[34;1m %-32s\033[0m" $i ${name%:*}
        test $[i % 2] -eq 0 && echo
        let i++
    done
    echo
}

openApi() {
    local apifile container
    apifile=$apiDir/${1#*:}
    container=${2-w3m}

    # echo $apifile

    case "$container" in
        "w3m")
            w3m $apifile
            ;;
        "less")
            w3m -dump $apifile | less
            ;;
        "chrome")
            chromium-browser $apifile &
            ;;
        "firefox")
            firefox $apifile
            ;;
        *)
    esac
}

searchKey() {
    getFindList $1

    local listLen=${#list[*]}
    test $listLen -eq 0 && err_exit "没有找到 \033[31m$1\033[0m 相关的结果!"

    if test $listLen -eq 1 ; then
        # echo ${list[1]}
        openApi ${list[1]} $2
        return
    fi

    while true ; do
        showList $1
        read -p "请输入编号选择: " num
        test "x$num" = "x" -o "x$num" = "xq" && break
        # echo ${list[$num]}
        openApi ${list[$num]} $2
    done
}

# 按全文关键词模糊查找

test -z "$1" && exit

case "$1" in
    down)
        downApi
        ;;
    index)
        genIndex
        ;;
    gpkg)
        genPackagePath
        ;;
    html)
        chromium-browser $workdir/index.html &
        ;;
    install)
        genIndex
        downApi
        ;;
    *)
        searchKey "$1" $2
        ;;
esac


